package com.zzz.common.redis.config;

import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @BelongsProject: oj-project
 * @BelongsPackage: com.zzz.common.redis.config
 * @Author: zhai
 * @CreateTime: 2025-09-23  11:34
 * @Description: TODO redis配置
 * @Version: 1.0
 */
@Configuration
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisConfig extends CachingConfigurerSupport {
    
    /**
     * TODO: 配置自定义RedisTemplate
     * 用于设置Redis的key和value的序列化方式，避免默认序列化带来的问题
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        // 设置Redis连接工厂
        template.setConnectionFactory(connectionFactory);
        
        // 使用自定义的JSON序列化器处理value
        JsonRedisSerializer serializer = new JsonRedisSerializer(Object.class);
        
        // 配置key的序列化方式为StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        // 配置value的序列化方式为自定义JSON序列化器
        template.setValueSerializer(serializer);
        
        // 配置Hash结构的key序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        // 配置Hash结构的value序列化方式
        template.setHashValueSerializer(serializer);
        
        // 初始化RedisTemplate的参数设置
        template.afterPropertiesSet();
        
        return template;
    }
}
    